package cn.seaboot.excel;

import cn.seaboot.commons.core.ClassPathResource;
import cn.seaboot.commons.file.IOUtils;
import cn.seaboot.excel.sax.ExcelContext;
import cn.seaboot.excel.sax.TableTemplate;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mr.css
 * @version 2025-06-30 17:20
 */
public class HtmlToExcelTpl {

    public static void main(String[] args) throws IOException, DocumentException {
        String file = "table.html";

        // table-header data
        Map<String, Object> head = new HashMap<>();
        head.put("title", "this is title!");
        head.put("dept", "生产部门!");

        // table-content data
        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, Object> item = new HashMap<>();
        int n = 9;
        while(n --> 0){
            item.put("field0" + n, "field0" + n);
            item.put("field1" + n, "field1" + n);
        }

        data.add(item);
        data.add(item);
        data.add(item);
        data.add(item);
        data.add(item);

        // 一个设计好的表格处理器
        TableTemplate parser = new TableTemplate();
        parser.setHeadData(head);
        parser.setBodyData(data);

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet();

            // excel 上下文
            ExcelContext context = new ExcelContext();
            context.setSheet(sheet);
            parser.setContext(context);

            // 解析 dom 文件，并将内容映射到 excel
            try (InputStream is = ClassPathResource.getInputStream(file)) {
                SAXReader reader = new SAXReader();
                Document document = reader.read(is);

                Element table = document.getRootElement();

                parser.parse(table);
            }

            // 保存生成的 excel
            try (OutputStream os = IOUtils.openFileOutputStream("C:\\Users\\ASUS\\Desktop\\ret.xlsx")) {
                workbook.write(os);
            }
        }
    }
}
